/**
 * @description 网络请求 axios封装
 */

import axios from 'axios'
import { getToken } from '@/common/auth'
import { Toast } from 'vant'
import { ToastFail } from '@/common/Toast'
// import router from '@/router';
// import $store from '@/store';

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 20000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    let token = getToken()
    if (token) {
      config.headers['token'] = token
    }
    Toast.loading({
      forbidClick: true,
      duration: 0,
    })
    return config
  },
  (error) => {
    Toast.clear()
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

//响应拦截器
service.interceptors.response.use(
  (res) => {
    Toast.clear()
    const data = res.data || {}
    return Promise.resolve(data)
  },
  (error) => {
    Toast.clear()
    if (error && error.response) {
      const { response } = error
      switch (response.status) {
        case 460:
          ToastFail('账号异地登录, 请重新授权').then(() => {
            // $store.dispatch("user/clearInfo")
            // router.push({ name: 'Login' })
          })
          break
        case 461:
          ToastFail('登录过期, 请重新授权').then(() => {
            // $store.dispatch("user/clearInfo")
            // router.push({ name: 'Login' })
          })
          break
        case 401:
          ToastFail('授权失败, 请重新授权').then(() => {
            // $store.dispatch("user/clearInfo")
            // router.push({ name: 'Login' })
          })
          break
        default:
          Toast({
            type: 'error',
            message: response.data.msg,
            showClose: true,
          })
          return Promise.reject(response)
      }
    }
  }
)

//get
export const $get = (url, params = {}, responseType = 'json') => {
  return service.get(url, {
    params: params,
    responseType: responseType,
  })
}

// 获取图片
export const $getCode = (url, params = {}) => {
  return service({
    method: 'get',
    url,
    params: params,
    responseType: 'blob',
  })
}

//post
export const $post = (url, params = {}, contentType = 'application/json') => {
  return service.post(url, params, {
    headers: {
      'Content-Type': contentType,
    },
  })
}
